package com.zh.chat.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.tree.DefaultTreeModel;

import com.zh.chat.controller.ClientContext;
import com.zh.chat.entity.Friend;
import com.zh.chat.entity.User;
import com.zh.chat.entity.UserInfo;
import com.zh.chat.entity.UserStatus;
import com.zh.chat.gui.lable.ImageZoomLb;
import com.zh.chat.gui.tree.FriendsPanel;
import com.zh.chat.gui.tree.GroupPanel;
import com.zh.chat.gui.tree.IconTreeNode;
import com.zh.chat.monitor.FileChangeAdapter;
import com.zh.chat.monitor.FileMonitor;
import com.zh.chat.util.FileOperationUtil;
import com.zh.chat.util.FileType;


/**
 * 软件主界面
 * @author 逍遥の剑仙
 * 2013-3-1
 */
public class MainFrame extends javax.swing.JFrame {

	private static final long serialVersionUID = 5409837602473459018L;

	private ImageZoomLb sculpture;
	private ImageZoomLb smallIcon;
	public void setSmallIcon(Icon smallIcon) {
		this.smallIcon.setIcon(smallIcon);
	}

	public void setSculptureIcon(Icon sculptureIcon) {
		this.sculpture.setIcon(sculptureIcon);
	}
	private JLabel nickNamelb;
	private JScrollPane groupJSPane;
	private JScrollPane friendJSPane;

	private MainFrameStatusPopBtn statusBtn;
	
	public void setStatus(int status) {
		statusBtn.setStatus(status);
	}
	
	private JPanel centerPanel;
	private JPanel headPanel;
	private JPanel contentPane;
	private JTabbedPane mutilPane;
	private FriendsPanel friendsPanel;
	private GroupPanel groupPanel;
	
	private JLabel loadingImg = null;
	private TrayManager trayManager = new TrayManager();//托盘图标
	private ClientContext clientContext = null;
	public void setClientContext(ClientContext clientContext) {
		this.clientContext = clientContext;
		statusBtn.setClientContext(clientContext);
		trayManager.setClientContext(clientContext);
	}
	
	public MainFrame(String lookAndFeel) {
		super();
		{
			//Set Look & Feel
			try {
				javax.swing.UIManager.setLookAndFeel(lookAndFeel);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		initGUI();
	}
	
	private void initGUI() {
		try {
			BorderLayout thisLayout = new BorderLayout();
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			{//设置左上角的图标
				URL url = this.getClass().getClassLoader().getResource("com/zh/chat/image/icon/32px.png");
				setIconImage(Toolkit.getDefaultToolkit().createImage(url));
			}
			getContentPane().setLayout(thisLayout);
			{
				contentPane = new JPanel();
				BoxLayout contentPaneLayout = new BoxLayout(contentPane, javax.swing.BoxLayout.Y_AXIS);
				contentPane.setLayout(contentPaneLayout);
				getContentPane().add(contentPane);
				contentPane.setBackground(new java.awt.Color(223,228,255));
				contentPane.setMinimumSize(new java.awt.Dimension(50, 100));
				{
					headPanel = new JPanel();
					contentPane.add(headPanel);
					headPanel.setPreferredSize(new java.awt.Dimension(231, 70));
					headPanel.setLayout(null);
					headPanel.setOpaque(false);
					headPanel.setMinimumSize(new java.awt.Dimension(200, 75));
					{
						nickNamelb = new JLabel();
						headPanel.add(nickNamelb);
						nickNamelb.setBounds(81, 11, 138, 20);
						nickNamelb.setText("\u6b63\u5728\u52a0\u8f7d\u6635\u79f0");
						nickNamelb.setFont(new java.awt.Font("新宋体",0,14));
					}
					{
						statusBtn = new MainFrameStatusPopBtn();
						statusBtn.setBounds(81, 39, 71, 20);
						headPanel.add(statusBtn);
						statusBtn.setFont(new java.awt.Font("新宋体",0,14));
					}
					this.sculpture = new ImageZoomLb();
					this.sculpture.setImage("src/com/zh/chat/image/icon/48px_offline.png", ImageZoomLb.ShowStyle.ZOOM);
					sculpture.setBorder(new LineBorder(Color.LIGHT_GRAY));
					sculpture.setLayout(null);
					sculpture.addMouseListener(new MouseAdapter() {
						public void mouseClicked(MouseEvent e) {
							clientContext.showUserInfoFrame();
						}
					});
					smallIcon = new ImageZoomLb();
					smallIcon.setBounds(41, 41, 18, 18);
					sculpture.add(smallIcon);
					sculpture.setBounds(2, 2, 65, 65);
					headPanel.add(sculpture);
				}
				{
					centerPanel = new JPanel();
					centerPanel.setLayout(new BorderLayout());
					centerPanel.setPreferredSize(new java.awt.Dimension(231, 401));
					contentPane.add(centerPanel);
					{
						URL loadingImgURL = MainFrame.class.getClassLoader().getResource("com/zh/chat/image/loading.gif");
						loadingImg = new JLabel(new ImageIcon(loadingImgURL));
						centerPanel.add(loadingImg, BorderLayout.CENTER);
						loadingImg.setSize(85, 85);
					}
					
				}
			}
			pack();
			this.setSize(247, 511);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowIconified(WindowEvent e) {
				MainFrame.this.setVisible(false);
				trayManager.initMainFrameTray(MainFrame.this);// 初始化系统托盘
			}

			@Override
			public void windowClosing(WindowEvent arg0) {
				boolean flag = clientContext.exit(MainFrame.this);
				if (flag) {
					trayManager.removeTray();
					clientContext.logout();
				}
			}
		});
	}
	public void initUserView(UserInfo userInfo) {
		FileMonitor monitor = FileMonitor.getInstance();
		String path = FileOperationUtil.getFilePath(FileType.SCULPTURE, userInfo.getSysId(), userInfo.getImage());
		monitor.addFileChangeListener(new FileChangeAdapter(){
			@Override
			public void fileExist(String filename) {
				sculpture.setImage(filename, ImageZoomLb.ShowStyle.ZOOM);//setIcon(new ImageIcon(filename));
				sculpture.setSize(65, 65);
				sculpture.repaint();
			}
			@Override
			public void fileNotExist(String filename) {
				//设置在线默认图标
				sculpture.setImage(offlineImg, ImageZoomLb.ShowStyle.ZOOM);
				sculpture.setSize(65, 65);
				sculpture.repaint();
			}
			@Override
			public void fileChanged(String filename) {
				sculpture.setImage(filename, ImageZoomLb.ShowStyle.ZOOM);//setIcon(new ImageIcon(filename));
				sculpture.setSize(48, 48);
				headPanel.repaint();
			}
		}, path, 2000);
		
		nickNamelb.setText(userInfo.getSysId() + "  " + userInfo.getNickname());
		int status = userInfo.getStatus();
		this.sculpture.setImage(onlineImg, ImageZoomLb.ShowStyle.ZOOM);
		statusBtn.setStatus(status);
		validate();
	}
	
	public void updateUserView(User user) {
		nickNamelb.setText(user.getSysId() + "  " + user.getNickname());
		statusBtn.setStatus(user.getStatus());
		String path = FileOperationUtil.getFilePath(FileType.SCULPTURE, user.getSysId(), user.getImage());
		this.sculpture.setImage(path, ImageZoomLb.ShowStyle.ZOOM);
		this.sculpture.repaint();
	}
	
	private void initCenterPane() {
		centerPanel.setOpaque(false);
		mutilPane = new JTabbedPane();
		centerPanel.add(mutilPane, BorderLayout.CENTER);
		mutilPane.setPreferredSize(new java.awt.Dimension(231, 391));
		{
			friendJSPane = new JScrollPane();
			mutilPane.addTab("好友列表", null, friendJSPane, null);
			friendJSPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
			{
				friendsPanel = new FriendsPanel();
				friendsPanel.setBackground(Color.PINK);
				friendsPanel.setClientContext(clientContext);// 添加控制器，使得好友列表监听器工作
				
				friendJSPane.setViewportView(friendsPanel);
				friendsPanel.setOpaque(false);
				friendsPanel.getJtree().setFont(new java.awt.Font("新宋体",0,12));
			}
		}
		{
			groupJSPane = new JScrollPane();
			mutilPane.addTab("我的群", null, groupJSPane, null);
			groupJSPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
			{
				groupPanel = new GroupPanel();
				groupJSPane.setViewportView(groupPanel);
				groupPanel.setOpaque(false);
				groupPanel.getJtree().setFont(new java.awt.Font("新宋体",0,12));
			}
		}
	}
	
	public void initFriendsTree(UserInfo userInfo) {
		// TODO 将数据结构中的好友列表更新到视图中
		centerPanel.remove(loadingImg);
		initCenterPane();
		ArrayList<Friend> list = userInfo.getFriends(3);
		DefaultTreeModel treeModel = friendsPanel.getTreeModel();
		if (list.size() != 0) {
			IconTreeNode rootNode = updateTree(list,
					(IconTreeNode) treeModel.getRoot());
			treeModel.setRoot(rootNode);
		}
		this.validate();
	}
	
	/**
	 * 更新好友树
	 * @param userInfo
	 */
	public void updateFriendsTree(UserInfo userInfo) {
		ArrayList<Friend> list = userInfo.getFriends(3);
		DefaultTreeModel treeModel = friendsPanel.getTreeModel();
		IconTreeNode rootNode = updateTree(list,new IconTreeNode("all"));
		treeModel.setRoot(rootNode);
		friendsPanel.getJtree().updateUI();
	}

	private IconTreeNode updateTree(ArrayList<Friend> list, IconTreeNode node) {
		IconTreeNode root = node;
		ArrayList<String> divide = new ArrayList<String>();
		for (Friend friend : list) {
			String divname = friend.getDivideName();
			if (!divide.contains(divname)) {
				divide.add(divname);
				IconTreeNode itn = new IconTreeNode(divname);
				for (Friend fri : list) {
					if (fri.getDivideName().equals(divname)) {
						itn.add(new IconTreeNode(fri));
					}
				}
				root.add(itn);
			}
		}
		return root;
	}
	
	private String offlineImg = "src/com/zh/chat/image/icon/48px_offline.png";
	private String onlineImg = "src/com/zh/chat/image/icon/48px.png";

	public void reset() {
		this.setStatus(UserStatus.OUTLINE);
	}

	public void setOfflineIcon() {
		this.sculpture.setImage(offlineImg, ImageZoomLb.ShowStyle.ZOOM);
	}
}
